package net.hn.hnms.sys.system.remote;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import net.hn.hnms.sys.common.core.constant.UserConstants;
import net.hn.hnms.sys.common.core.enums.UserStatus;
import net.hn.hnms.sys.common.core.exception.ServiceException;
import net.hn.hnms.sys.common.core.exception.user.UserException;
import net.hn.hnms.sys.common.core.utils.tool.Func;
import net.hn.hnms.sys.system.api.domain.SysDept;
import net.hn.hnms.sys.system.api.domain.SysUser;
import net.hn.hnms.sys.system.api.model.LoginUser;
import net.hn.hnms.sys.system.api.model.RoleDTO;
import net.hn.hnms.sys.system.api.model.UserVo;
import net.hn.hnms.sys.system.api.model.XcxLoginUser;
import net.hn.hnms.sys.system.mapper.SysDeptMapper;
import net.hn.hnms.sys.system.service.ISysConfigService;
import net.hn.hnms.sys.system.service.ISysPermissionService;
import net.hn.hnms.sys.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 操作日志记录
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class RemoteUserServiceImpl {

    private final ISysUserService userService;
    private final ISysPermissionService permissionService;
    private final ISysConfigService configService;
    private final SysDeptMapper baseMapper;

    public LoginUser getUserInfo(String username) throws UserException {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (ObjectUtil.isNull(sysUser)) {
            throw new UserException("user.not.exists", username);
        }
        if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            throw new UserException("user.password.delete", username);
        }
        if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            throw new UserException("user.blocked", username);
        }
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        return buildLoginUser(sysUser);
    }

    public LoginUser getUserInfoByPhonenumber(String phonenumber) throws UserException {
        SysUser sysUser = userService.selectUserByPhonenumber(phonenumber);
        if (ObjectUtil.isNull(sysUser)) {
            throw new UserException("user.not.exists", phonenumber);
        }
        if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            throw new UserException("user.password.delete", phonenumber);
        }
        if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            throw new UserException("user.blocked", phonenumber);
        }
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        return buildLoginUser(sysUser);
    }

    public XcxLoginUser getUserInfoByOpenid(String openid) throws UserException {
        // todo 自行实现 userService.selectUserByOpenid(openid);
        SysUser sysUser = new SysUser();
        if (ObjectUtil.isNull(sysUser)) {
            // todo 用户不存在 业务逻辑自行实现
        }
        if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            // todo 用户已被删除 业务逻辑自行实现
        }
        if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            // todo 用户已被停用 业务逻辑自行实现
        }
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        XcxLoginUser loginUser = new XcxLoginUser();
        loginUser.setUserId(sysUser.getUserId());
        loginUser.setUsername(sysUser.getUserName());
        loginUser.setUserType(sysUser.getUserType());
        loginUser.setOpenid(openid);
        return loginUser;
    }

    public Boolean registerUserInfo(SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            throw new ServiceException("当前系统没有开启注册功能");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) {
            throw new UserException("user.register.save.error", username);
        }
        return userService.registerUser(sysUser);
    }

    /**
     * 构建登录用户
     */
    private LoginUser buildLoginUser(SysUser user) {
        LoginUser loginUser = new LoginUser();
        SysDept dept = user.getDept();

        loginUser.setUserId(user.getUserId());
        if (Func.isNotEmpty(user.getDeptId()) && user.getDeptId().contains(",")){
            List<Long> longList = Func.toLongList(user.getDeptId());
            loginUser.setDeptId(longList.get(0));
        }else{
            loginUser.setDeptId(Long.valueOf(user.getDeptId()));
        }

        loginUser.setUsername(user.getUserName());
        loginUser.setNickname(user.getNickName());
        loginUser.setPassword(user.getPassword());
        loginUser.setUserType(user.getUserType());

        loginUser.setMenuPermission(permissionService.getMenuPermission(user.getUserId()));
        loginUser.setRolePermission(permissionService.getRolePermission(user.getUserId()));
        loginUser.setDeptName(ObjectUtil.isNull(user.getDept()) ? "" : user.getDept().getDeptName());
        List<RoleDTO> roles = BeanUtil.copyToList(user.getRoles(), RoleDTO.class);
        loginUser.setRoles(roles);
        while (dept != null) {
            if (StringUtils.isNotBlank(dept.getOrganizationCode())) {
                loginUser.setOrganizationCode(dept.getOrganizationCode());
                loginUser.setOrganizationId(dept.getDeptId());
                LambdaQueryWrapper<SysDept> childrenQuery = new LambdaQueryWrapper<>();
                childrenQuery.eq(SysDept::getParentId,dept.getDeptId());
                childrenQuery.isNotNull(SysDept::getOrganizationCode);
                childrenQuery.ne(SysDept::getOrganizationCode,"");
                loginUser.setContainOrgs(baseMapper.selectList(childrenQuery));
                break;
            } else {
                if (dept.getDeptId() == dept.getParentId()) break;
                dept = baseMapper.selectById(dept.getParentId());
            }
        }
        return loginUser;
    }


    /**
     * 通过用户名id查询用户信息
     *
     * @param id 用户名id
     * @return 结果
     */
    public LoginUser getUserInfoById(Long id) {
        SysUser user = userService.selectUserById(id);
        return buildSimpleLoginUser(user);
    }

    /**
     * SysUser 转 LoginUser 仅包含简单信息
     *
     * @param user 用户
     * @return 结果
     */
    private LoginUser buildSimpleLoginUser(SysUser user) {
        if (user == null) {
            return null;
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUsername(user.getUserName());
//        loginUser.setDeptId(user.getDeptId());
        if (Func.isNotEmpty(user.getDeptId()) && user.getDeptId().contains(",")){
            List<Long> longList = Func.toLongList(user.getDeptId());
            loginUser.setDeptId(longList.get(0));
        }else{
            loginUser.setDeptId(Long.valueOf(user.getDeptId()));
        }
        loginUser.setDeptName(user.getDept().getDeptName());
        loginUser.setNickname(user.getNickName());
        return loginUser;
    }


    /**
     * 通过用户id查询用户信息
     *
     * @param username 用户名称
     * @return 结果
     */
    public List<LoginUser> getUserListByUserName(String username) {
        SysUser query = new SysUser();
        query.setUserName(username);
        List<SysUser> sysUsers = userService.selectUserList(query);
        if (CollUtil.isEmpty(sysUsers)) {
            return ListUtil.empty();
        }
        return sysUsers.stream().map(this::buildSimpleLoginUser).collect(Collectors.toList());
    }
    /**
     * 通过用户中文查询用户信息集合
     *
     * @param username 用户中文名称
     * @return 结果
     */
    public List<LoginUser> getUserListByChUserName(String username) {
//        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
//        query.like(SysUser::getNickName, username);
//        query.eq(SysUser::getDelFlag,0);
//        List<SysUser> sysUsers = userService.list(query);;
//        if (CollUtil.isEmpty(sysUsers)) {
//            return ListUtil.empty();
//        }
//        return sysUsers.stream().map(this::buildSimpleLoginUser).collect(Collectors.toList());

        SysUser query = new SysUser();
        query.setNickName(username);
        List<SysUser> sysUsers = userService.selectUserList(query);
        if (CollUtil.isEmpty(sysUsers)) {
            return ListUtil.empty();
        }
        return sysUsers.stream().map(this::buildSimpleLoginUser).collect(Collectors.toList());
    }

    /**
     * 通过用户id集合查询用户信息
     *
     * @param idList 用户集合
     * @return 结果
     */
    public List<LoginUser> getUserListByIdList(Collection<Long> idList) {
        if (CollUtil.isEmpty(idList)) {
            return ListUtil.empty();
        }
        List<SysUser> sysUsers = userService.selectUserList(new LambdaQueryWrapper<SysUser>()
                .in(SysUser::getUserId, idList));
        return sysUsers.stream().map(this::buildSimpleLoginUser).collect(Collectors.toList());
    }

    /**
     * 通过用户idCard集合查询用户信息
     *
     * @param idCardList 用户集合
     * @return 结果
     */
    public List<String> getUserListByIdCardList(Collection<String> idCardList) {
        if (CollUtil.isEmpty(idCardList)) {
            return ListUtil.empty();
        }
        List<SysUser> sysUsers = userService.selectUserList(new LambdaQueryWrapper<SysUser>()
                .in(SysUser::getIdCard, idCardList));
        return sysUsers.stream().map(SysUser::getUserName).collect(Collectors.toList());
    }

    public List<String> getUserListByDept(Collection<Long> depts) {
        if (CollUtil.isEmpty(depts)) {
            return ListUtil.empty();
        }
        List<SysUser> sysUsers = userService.selectUserList(new QueryWrapper<SysUser>()
                .in("u.dept_id", depts));
        return sysUsers.stream().map(SysUser::getUserName).collect(Collectors.toList());
    }

    /**
     * SysUser 转 User 仅包含简单信息
     *
     * @param user 用户
     * @return 结果
     */
    private UserVo buildSimpleUser(SysUser user) {
        if (user == null) {
            return null;
        }
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user, userVo);

        return userVo;
    }

    public UserVo getUserById(Long id) {
        SysUser user = userService.selectUserById(id);
        return buildSimpleUser(user);
    }

    /**
     * 通过用户名ids查询Sys用户信息
     *
     * @param idList
     * @return
     */
    public List<UserVo> getUserListIds(Collection<Long> idList) {
        if (CollUtil.isEmpty(idList)) {
            return ListUtil.empty();
        }
        List<SysUser> sysUsers = userService.selectUserList(new LambdaQueryWrapper<SysUser>()
                .in(SysUser::getUserId, idList));
        return buildListUser(sysUsers);
    }

    //批量封装用户Vo
    private List<UserVo> buildListUser(List<SysUser> user) {
        if (user.isEmpty()) {
            return new ArrayList<>();
        }
        return user.stream().map(t -> {
            UserVo userVo = new UserVo();
            //用户id
            userVo.setUserId(t.getUserId());
            //用户昵称
            userVo.setNickName(t.getNickName());
            //用户名字
            userVo.setUserName(t.getUserName());
            //部门id
//            userVo.setDeptId(t.getDeptId());
            if (Func.isNotEmpty(t.getDeptId()) && t.getDeptId().contains(",")){
                List<Long> longList = Func.toLongList(t.getDeptId());
                userVo.setDeptId(longList.get(0));
            }else{
                userVo.setDeptId(Long.valueOf(t.getDeptId()));
            }
            return userVo;
        }).collect(Collectors.toList());
    }

    /**
     * 获取所有用户信息
     *
     * @return
     */
    public List<UserVo> getUserAllList() {
        List<SysUser> sysUsers = userService.selectUserAllList();
        return buildListUser(sysUsers);
    }

    /**
     * 获取排除Ids的用户列表
     *
     * @param idList
     * @return
     */
    public List<UserVo> getUserListExcludeIds(Collection<Long> idList) {
        List<SysUser> sysUsers = userService.selectUserExcludeList(idList);
        return buildListUser(sysUsers);
    }
}
